<?PHP
/**
 * RSA加密解密
 */
class rsa
{
	private static $_instance = null;
	private $private_key      = null;
	private $public_key       = null;
	private $config;

	/**
	 * 获取公钥文件
	 * @method getPublic
	 * @return [type]    [description]
	 * @author NewFuture
	 */
	public static function getPublic()
	{
		$instance = self::getInstance();
		return file_get_contents($instance->config['publicpath']);
	}

	/**
	 * 解密
	 * @method decode
	 * @return [type] [description]
	 * @author NewFuture
	 */
	public static function decode($str)
	{
		$str      = base64_decode($str);
		$instance = self::getInstance();
		if (openssl_private_decrypt($str, $decrypted, $instance->getPrivateKey()))
		{
			return $decrypted;
		}
		else
		{
			return false;
		}
	}

	/**
	 * 加密
	 * @method encode
	 * @param  [type] $str [原文]
	 * @return [type]      [description]
	 * @author NewFuture
	 */
	public static function encode($str)
	{
		$instance = self::getInstance();
		if (openssl_public_encrypt($str, $crypttext, $instance->getPublicKey()))
		{
			return base64_encode($crypttext);
		}
		else
		{
			return false;
		}
	}

	/**
	 * 获取实体对象
	 * @method getInstance
	 * @return [type]      [description]
	 * @author NewFuture
	 */
	public static function getInstance()
	{
		if (null === self::$_instance)
		{
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * 获取私钥
	 * @method getkey
	 * @return [type] [description]
	 * @author NewFuture
	 */
	private function getPrivateKey()
	{
		if (null === $this->private_key)
		{
			$file_path         = $this->config['privatepath'];
			$priv_file         = file_get_contents($file_path);
			$this->private_key = openssl_pkey_get_private($priv_file);
		}
		return $this->private_key;
	}

	/**
	 * 获取公钥
	 * @method getPublicKey
	 * @return [type]       [description]
	 * @author NewFuture
	 */
	private function getPublicKey()
	{
		if (null === $this->public_key)
		{
			$file_path        = $this->config['publicpath'];
			$content          = file_get_contents($file_path);
			$this->public_key = openssl_pkey_get_public($content);
		}
		return $this->public_key;
	}

	private function __construct()
	{
		$this->config = Yaf_Registry::get('config')['rsa'];
	}
}